package com.dayi.fragment;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.AnswerDetail;
import com.dayi.fragment.child.TeacherAnswerListFragment;
import com.dayi.utils.pop.AskStateListPopupUtils;
import com.dayi.utils.pop.PayStatePopupUtils;
import com.lib.app.ARouterPathUtils;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.px_dp.DisplayUtil;
import com.lib.fastkit.views.load_state_view.MultiStateView;
import com.lib.fastkit.views.spring_refresh.container.DefaultFooter;
import com.lib.fastkit.views.spring_refresh.container.DefaultHeader;
import com.lib.fastkit.views.spring_refresh.widget.SpringView;
import com.lib.fastkit.views.viewpager.my.ViewPagerForScrollView;
import com.lib.ui.fragment.BaseAppFragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathUtils.Dayi_SiXueFragment_1)
public class SiXueFragment_1 extends BaseAppFragment {

    @BindView(R2.id.state_view)
    MultiStateView stateView;
    @BindView(R2.id.springView)
    SpringView springView;

    //未登录和学生展示控件
    @BindView(R2.id.lin_student)
    LinearLayout linStudent;
    @BindView(R2.id.iv_askstate)
    ImageView ivAskstate;
    @BindView(R2.id.fr_state)
    FrameLayout frState;
    @BindView(R2.id.iv_ask)
    ImageView ivAsk;

    //老师展示控件
    @BindView(R2.id.lin_teacher)
    LinearLayout linTeacher;
    @BindView(R2.id.tv_stu_num_bg)
    TextView tvStuNumBg;//用于显示文字背后的下划线背景，和文本设置一样的值
    @BindView(R2.id.tv_stu_num)
    TextView tvStuNum;
    @BindView(R2.id.tv_money_num_bg)
    TextView tvMoneyNumBg;
    @BindView(R2.id.tv_money_num)
    TextView tvMoneyNum;
    @BindView(R2.id.lin_title)
    LinearLayout linTitle;
    @BindView(R2.id.contentViewPager)
    ViewPagerForScrollView contentViewPager;
    @BindView(R2.id.indicator2)
    LinearLayout linIndicator2;

    private String teaList[] = {"最新提问", "问答记录"};
    private int lastPosition2 = 0;
    private List<Fragment> fragments = new ArrayList<>();

    private List<AnswerDetail> stateList = new ArrayList<>();

    private String[] gradeArr, subjArr;

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        stateView.setMultiStateViewLisener(new MultiStateView.MultiStateViewLisener() {
            @Override
            public void onTryAgain() {
                initAskState();
            }
        });

        if ("1".equals(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity())) {
            linTeacher.setVisibility(View.VISIBLE);
            linStudent.setVisibility(View.GONE);
        } else {
            linTeacher.setVisibility(View.GONE);
            linStudent.setVisibility(View.VISIBLE);
        }

//        linTeacher.setVisibility(View.GONE);
//        linStudent.setVisibility(View.VISIBLE);

        initAskState();

        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setFooter(new DefaultFooter(getActivity()));
        springView.setEnableHeader(false);
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadmore() {

            }
        });

        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

        initBottomStageViewPager();

        gradeArr = getActivity().getResources().getStringArray(R.array.array_choose_grade);
        subjArr = getActivity().getResources().getStringArray(R.array.array_choose_subject);

    }

    @Override
    public void onResume() {
        super.onResume();

        if ("1".equals(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity())) {
            linTeacher.setVisibility(View.VISIBLE);
            linStudent.setVisibility(View.GONE);
        } else {
            linTeacher.setVisibility(View.GONE);
            linStudent.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R2.id.fr_state, R2.id.iv_ask})
    public void onViewClicked(final View view) {

        int i = view.getId();
        if (i == R.id.fr_state) {

            AskStateListPopupUtils stateListPopupUtils = new AskStateListPopupUtils(getActivity());
            //更新提问列表数据
            stateListPopupUtils.updateStateList(stateList);
            stateListPopupUtils.showAnswerPopuPopu(view);
        } else if (i == R.id.iv_ask) {
//            getWechatApi();

//            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
//                    .withString("urlPath", "https://h5.xuesituedu.com/activity/welfare.html").navigation();

            showChooseDialog(view);

        }
    }

    private void showChooseDialog(final View fragmentView) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_askchoose_1, null);

        ImageView iv_hide = view.findViewById(R.id.iv_hide);

        Spinner spinGrade = view.findViewById(R.id.spin_grade);
        Spinner spinSubj = view.findViewById(R.id.spin_subj);

        spinGrade.setDropDownVerticalOffset(112);
        spinSubj.setDropDownVerticalOffset(112);

        try {
            Field popup = Spinner.class.getDeclaredField("mPopup");
            Field popup1 = Spinner.class.getDeclaredField("mPopup");
            popup.setAccessible(true);
            popup1.setAccessible(true);

            // Get private mPopup member variable and try cast to ListPopupWindow
            ListPopupWindow popupWindow = (ListPopupWindow) popup.get(spinGrade);
            ListPopupWindow popupWindow1 = (ListPopupWindow) popup1.get(spinSubj);

            // Set popupWindow height to 500px
            popupWindow.setHeight(600);
            popupWindow1.setHeight(600);
        } catch (Exception e) {
            // silently fail...
            LogUtil.e("Exception为：" + e.getMessage().toString());
        }

        spinGrade.setAdapter(new TvArrayAdapter(getActivity(), gradeArr));
        spinSubj.setAdapter(new TvArrayAdapter(getActivity(), subjArr));

        TextView tvMoney = view.findViewById(R.id.tv_money);
        LinearLayout linPay = view.findViewById(R.id.lin_pay);

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setView(view)
                .setCancelable(true)
                .show();

        spinGrade.setOnItemSelectedListener(new GradeSpinnerAdapter());
        spinSubj.setOnItemSelectedListener(new SubjectSpinnerAdapter());

        //给问题赋值金额
        tvMoney.setText("15");

        iv_hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        linPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PayStatePopupUtils payStatePopupUtils = new PayStatePopupUtils(getActivity());
                payStatePopupUtils.setPayState("支付成功", "支付成功开始问问题吧", "去拍照");
                payStatePopupUtils.setPayStateUtilsListener(new PayStatePopupUtils.PayStateUtilsListener() {
                    @Override
                    public void onSure() {
                        ARouter.getInstance().build(ARouterPathUtils.Dayi_RoomStudent).navigation();
                    }
                });
                payStatePopupUtils.showAnswerPopuPopu(fragmentView);
                dialog.dismiss();
            }
        });


    }


    private void getWechatApi() {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            // TODO: handle exception
            showToast("检查到您手机没有安装微信，请安装后使用该功能");
        }
    }

    private void initAskState() {

        AnswerDetail answerDetail1 = new AnswerDetail();
        AnswerDetail answerDetail2 = new AnswerDetail();

        AnswerDetail.ObjBean objBean1 = new AnswerDetail.ObjBean();
        objBean1.setIs_check(0);
        objBean1.setCorrect("三年级数学");
        answerDetail1.setObj(objBean1);

        AnswerDetail.ObjBean objBean2 = new AnswerDetail.ObjBean();
        objBean2.setIs_check(1);
        objBean2.setCorrect("高一英语");
        answerDetail2.setObj(objBean2);

        stateList.add(answerDetail1);
        stateList.add(answerDetail2);

    }

    @Override
    protected int getLayoutId() {

        return R.layout.fragment_sixue_1;
    }

    private DemandAdapter mDemandAdapter;

    private void initBottomStageViewPager() {
        lastPosition2 = 0;
        //下方ViewPager
        fragments.clear();

        for (int i = 0; i < teaList.length; i++) {
            fragments.add(new TeacherAnswerListFragment());
        }

        initBottomTitle();
        contentViewPager.setOffscreenPageLimit(2);
        mDemandAdapter = new DemandAdapter(getActivity().getSupportFragmentManager());
        contentViewPager.setAdapter(mDemandAdapter);
        contentViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                initTitle(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initTitle(0);
    }

    private List<View> listTitle = new ArrayList<>();

    private void initBottomTitle() {

        linTitle.removeAllViews();
        listTitle.clear();
        for (int i = 0; i < teaList.length; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_title, null);
            listTitle.add(view);
            final TextView tv_title = view.findViewById(R.id.tv_title);

            final View v_circle = view.findViewById(R.id.v_circle);
            tv_title.setText(teaList[i]);
            tv_title.setTextSize(14);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(DisplayUtil.dip2px(getActivity(), 16), 0, 0, 0);
            view.setLayoutParams(params);
            linTitle.addView(view);
            final int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    initTitle(finalI);
                }
            });

        }


    }

    private void initTitle(int position) {

        if (listTitle.size() > 0) {
            for (View view : listTitle) {

                TextView tv_title = view.findViewById(R.id.tv_title);
                View v_circle = view.findViewById(R.id.v_circle);
                v_circle.setVisibility(View.GONE);
                tv_title.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
            }

            contentViewPager.setCurrentItem(position);
            View view = listTitle.get(position);
            TextView tv_title = view.findViewById(R.id.tv_title);
            View v_circle = view.findViewById(R.id.v_circle);
            v_circle.setVisibility(View.VISIBLE);
            tv_title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
        }

    }

    /**
     * 适配器
     */
    public class DemandAdapter extends FragmentPagerAdapter {


        public DemandAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

    }


    class GradeSpinnerAdapter implements AdapterView.OnItemSelectedListener {


        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String item = (String) parent.getItemAtPosition(position);

            LogUtil.e("选中的年级为：" + item);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    class SubjectSpinnerAdapter implements AdapterView.OnItemSelectedListener {


        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String item = (String) parent.getItemAtPosition(position);

            LogUtil.e("选中的科目为：" + item);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }


    public class TvArrayAdapter extends BaseAdapter {

        private String[] mStringArray;
        private Context context;

        public TvArrayAdapter(Context context, String[] mStringArray) {
            this.context = context;
            this.mStringArray = mStringArray;
        }

        @Override
        public int getCount() {
            return mStringArray.length;
        }

        @Override
        public Object getItem(int position) {
            return mStringArray[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {

//            LayoutInflater inflate1 = LayoutInflater.from(context);
//            View view = inflate1.inflate(R.layout.popup_gradesubjselect, null);
//
//            RecyclerView rvSelect = view.findViewById(R.id.rv_select);
//            SelectAdapter selectAdapter = new SelectAdapter(context, mStringArray);
//            MyLinearLayoutManager manager = new MyLinearLayoutManager(getActivity());
//            rvSelect.setLayoutManager(manager);
//            rvSelect.setAdapter(selectAdapter);

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;

        }

    }

    class SelectAdapter extends RecyclerView.Adapter<SelectViewHolder> {

        private String[] mStringArray;
        private Context context;

        public SelectAdapter(Context context, String[] mStringArray) {
            this.context = context;
            this.mStringArray = mStringArray;
        }

        @Override
        public SelectViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {

            View view = LayoutInflater.from(context).inflate(R.layout.item_select, null);

            return new SelectViewHolder(view);
        }

        @Override
        public void onBindViewHolder(SelectViewHolder selectViewHolder, final int position) {

            selectViewHolder.tvText.setText(mStringArray[position]);
            selectViewHolder.linItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                }
            });

        }

        @Override
        public int getItemCount() {
            return mStringArray.length;
        }
    }


    class SelectViewHolder extends RecyclerView.ViewHolder {

        private TextView tvText;
        private LinearLayout linItem;

        public SelectViewHolder(View itemView) {
            super(itemView);

            tvText = itemView.findViewById(R.id.tv_text);
            linItem = itemView.findViewById(R.id.lin_item);

        }
    }


}
